package com.banyuan.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")  //拦截所有
public class AuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {


    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest; //强转，为了获取URI路径的方法

        String requestURI = request.getRequestURI();
        if (requestURI.contains("/user/log.jsp") || requestURI.contains("/user/show.jsp") || requestURI.contains("/user/log") || requestURI.contains("/user/read")) {
            // 不需要用户登录的页面，先不拦截，登陆的2个页面更不能拦截，不然没法登陆了
            // 评论是需要登陆的，阅读是不需要的，所有阅读写在了if判断条件里
            filterChain.doFilter(servletRequest, servletResponse);
            //放行
        } else {
            HttpSession session = request.getSession();
            Object user = session.getAttribute("user");
            // 获取当时登陆成功会存的session的值进行判断
            if (user == null) {
                //如果是null的话,就是没登陆成功，让他去重新登陆
                request.setAttribute("msg","你还没有登陆，请登陆");
                request.getRequestDispatcher("/user/log.jsp").forward(request,servletResponse);

            } else {
                //否则的话就是登陆成功的用户，直接放行
                filterChain.doFilter(servletRequest, servletResponse);//放行
            }
        }

    }

    @Override
    public void destroy() {

    }
}
